package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Role;
import com.itheima.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    //获取当前登录（认证）用户的用户名
    @RequestMapping("/getLoginUsername")
    public Result getLoginUsername(){
        try{
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            String password = user.getPassword();
            Collection<GrantedAuthority> authorities = user.getAuthorities();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }catch (Exception e){
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {


        PageResult pageResult = userService.findPage(queryPageBean);
        return pageResult;
    }


    @RequestMapping("/getRoles")
    public Result getRoles(){


        try {
            List<Role> roles = userService.getRoles();
            return new Result(true,"",roles);
        } catch (Exception e) {
            return new Result(true,"查询角色数据失败");
        }
    }

    @RequestMapping("/addUser")
    public Result addUser(@RequestBody com.itheima.pojo.User user,Integer[] roleIds){

        try {
            Boolean aBoolean = userService.checkUsername(user.getUsername());
            if(!aBoolean){
                return new Result(false,"新增用户失败,用户名已存在");
            }
            String password = user.getPassword();
            user.setPassword(passwordEncoder.encode(password));
            userService.addUser(user,roleIds);
            return new Result(true,"新增用户成功");
        } catch (Exception e) {
            return new Result(false,"新增用户失败");
        }
    }


    @RequestMapping("/findUserById")
    public Result findUserById(Integer id){
        try {
            com.itheima.pojo.User userById = userService.findUserById(id);
            return new Result(true,"",userById);
        } catch (Exception e) {
            return new Result(false,"查询用户数据失败");
        }
    }

    @RequestMapping("/findRoleIdsByUserId")
    public Result findRoleIdsByUserId(Integer userId){

        try {
            List<Integer> roleIds = userService.findRoleIdsByUserId(userId);
            return new Result(true,"",roleIds);
        } catch (Exception e) {
            return new Result(false, "获取角色信息失败");
        }
    }

    @RequestMapping("/edit")
    public Result edit(@RequestBody com.itheima.pojo.User user,Integer[] roleIds){
        try {
            Result result = userService.editUser(user, roleIds);
            return result;
        } catch (Exception e) {
            return new Result(false,"编辑用户信息失败");
        }
    }

    @RequestMapping("/deleteUser")
    public Result deleteUser(Integer id){

        try {
            userService.deleteUser(id);
        } catch (Exception e) {
            return new Result(false,"删除失败");
        }
        return new Result(true,"删除成功");
    }


    @RequestMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map map){

        try {
            com.itheima.pojo.User userById = userService.findUserById((Integer) map.get("id"));

            String password = (String) map.get("password");
            boolean matches = passwordEncoder.matches(password, userById.getPassword());
            if(!matches){
                return new Result(false,"旧密码输入错误，修改失败");
            }
            String newPassword = passwordEncoder.encode((String) map.get("newPassword"));
            map.put("password",newPassword);
            userService.updatePassword(map);
        } catch (Exception e) {
            return new Result(false,"密码修改失败");
        }
        return new Result(true,"密码修改成功");
    }
}
